<template>
  <div>
    <el-tabs
      v-model="activeIndex"
      :before-leave="nextStep"
    >
      <el-tab-pane label="基本信息" name="基本信息"></el-tab-pane>
      <el-tab-pane label="指标内容" name="指标内容"></el-tab-pane>
    </el-tabs>
    <div class="line"></div>

    <el-form ref="dataForm" 
      :model="form" 
      label-width="100px"
      label-position="left"
      class="el-form"
      :rules="rules"
      >
      <div v-if="activeIndex=='基本信息'">
        <el-form-item label="模板名称" prop="title">
          <el-input v-model="form.title" style="width: 450px;" placeholder="如“经理晋升模板、业务能力模板”"></el-input>
        </el-form-item>
        <el-form-item label="考核对象" prop="resource1">
          <el-radio-group v-model="form.resource1">
            <el-radio label="按对象评分"></el-radio>
            <el-radio label="按职位评分"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="指标评分" prop="resource2">
          <el-radio-group v-model="form.resource2">
            <el-radio label="按分数"></el-radio>
            <el-radio label="按权重"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="评分标准" prop="template">
          <el-select v-model="form.template" style="width: 350px;" placeholder="请选择考核模板">
            <el-option 
              v-for="item in allTemplate"
              :key="item.title"
              :label="item.title"
              :value="item.title"
              ></el-option>
          </el-select>
        </el-form-item>
      </div>
    </el-form>

    <div class="eva-con" v-if="activeIndex=='指标内容'">
        <div class="left-menu">
          <div class="left-menu-top">
            <span>指标组</span>
            <el-popover
              v-model:visible="ppVisible"
              placement="bottom-start"
              ref="ppLeftTop"
              trigger="click"
              width="300"
              @after-leave="ppCancel"
              >
              <template #reference>
                <span class="el-dropdown-link">
                  <button class="btn-color left-top-btn">添加</button>
                </span>
              </template>
                <el-row style="width: 300px">
                  <el-col>
                    <div style="font-weight: 800;color: rgb(106,104,115)">指标组名称</div>
                    <el-input
                      v-model="addEvaGroupTitle"
                      maxlength="15"
                      show-word-limit
                      type="text"
                    />
                    <div style="font-size: 12px;margin-top:8px">仅支持数字、字母、减号、下划线和点</div>
                  </el-col>
                  <el-col style="margin-top: 15px">
                    <div style="font-weight: 800;color: rgb(106,104,115)">排序</div>
                    <el-input
                      v-model="addEvaGroupSort"
                      maxlength="3"
                      show-word-limit
                      type="text"
                    />
                    <div style="font-size: 12px;margin-top:8px">在列表与考核详情中，按数字从大到小排序</div>
                  </el-col>
                  <el-col style="margin-top: 15px;padding-left:150px">
                    <el-button size="mini" class="close-btn" @click="ppCancel">取消</el-button>
                    <el-button size="mini" class="btn-color" @click="addOrUpdateEvaGroup()">确定</el-button>
                  </el-col>
                </el-row>
            </el-popover>
          </div>
          <div class="left-menu-con">
            <div class="left-menu-item" :class="{'left-menu-item-active': currentEva == index}" v-for="(item,index) in evaGroup" :key="item.title">
              <div class="left-menu-item-con" @click="currentShowEva(index)">
                <i class="el-icon-folder"></i>
                <span v-text="item.title"></span>
                <span>({{item.score}})</span>
              </div>
              <div class="left-menu-icon">
                <el-dropdown>
                  <span class="el-dropdown-link">
                    <i class="el-icon-more cursor" style="font-size: 24px;"></i>
                    <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click.native="updateEvaGroup(index)">编辑</el-dropdown-item>
                      <el-dropdown-item @click="deleteEvaGroup(index)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </div>
        <div class="right-menu">
          <div class="right-menu-top">
            <div class="right-box-btn">
              <button class="btn-color right-top-btn" @click="showAddEvaHandle">从指标库中添加指标</button>
            </div>
          </div>
          <div class="line-sep"></div>
          <div class="right-menu-con">
            <el-table 
              :data="tableData[currentEva]" 
              ref="tableData"
              v-loading="dataListLoading"
              border
              class="right-table"
              :header-cell-style="{background: '#f7f7f7'}"
            >
              <el-table-column prop="title" label="名称" />
              <el-table-column prop="type" label="类型" width="180" />
              <el-table-column prop="score" label="满分" width="80" />
              <el-table-column width="60" label="操作" >
                <template #default="scope">
                    <el-dropdown>
                        <span class="el-dropdown-link">
                            <i class="el-icon-more cursor" style="font-size: 28px"></i>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="deleteEvaItem(scope.$index)">删除</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    <div class="line-sep" style="margin-top: 25px"></div>
    <div class="btn">
        <el-button class="btn-color" v-if="activeIndex=='基本信息'" @click="nextStep">下一步</el-button>
        <el-button class="close-btn" v-if="activeIndex=='指标内容'" @click="activeIndex='基本信息'">返回</el-button>
        <el-button class="btn-color" v-if="activeIndex=='指标内容'" @click="onSubmit">保存</el-button>
    </div>
    <exam-template-add-eva ref="addEva" :evaItem="tableData[currentEva]"  @refrashData="updateTableData"></exam-template-add-eva>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import ExamTemplateAddEva from './ExamTemplateAddEva.vue'
export default {
  components: {
    ExamTemplateAddEva
  },
  data() {
    return {
      dataListLoading: false,
      form: {
        title: '',
        template: '',
        resource1: '按对象评分',
        resource2: '按分数',
      },
      tableData: [],
      allTemplate: [], // 考核模板内容
      // Tabs 标签页默认激活的index  也是显示的页面  基本信息  指标内容
      activeIndex: '基本信息',
      // 指标组
      evaGroup: [],
      // 显示隐藏 弹出框
      ppVisible: false,
      // 新建指标组的名称
      addEvaGroupTitle: '',
      // 新建指标组的排序
      addEvaGroupSort: '',
      // 编辑功能 当前是哪个元素
      currentEvaGroup: -1,
      // 显示对应指标组的 指标（右边的指标）
      currentEva: 0,
      rules: {
        title:  [
          { required: true, message: '请输入考核名称', trigger: 'blur' },
        ],
        template:  [
          { required: true, message: '请选择考核模板', trigger: 'blur' },
        ],
        resource1:  [
          { required: true, message: '请输入考核对象', trigger: 'blur' },
        ],
        resource2:  [
          { required: true, message: '请输入指标评分', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    setTimeout(() => {
      this.getAllTemplate() // 获取考核模板
      this.init()
    }, 0)
  },
  methods: {
    init() {
      // let id = this.$route.params.id=="undefined" ? null : this.$route.params.id
      let id = this.$route.params.id
      // 有id 编辑
      if (id) {
        this.$http('markTemplate/selectTemplateListById', 'post', {id}, false, resp => {
          if (resp.code == 200) {
            // console.log(resp);
            let {data} = resp
            this.form.title = data.title
            this.allTemplate.forEach(item => {
              if (item.id == data.examRankId) {
                this.form.template = item.title
                return
              }
            })
            let options = JSON.parse(data.options)
            // console.log(options);
            options.forEach((item,index) => {
              let evaGroup = {
                title: item.title,
                score: item.score,
                sort: item.sort
              }
              this.evaGroup[index] = (evaGroup)
              this.tableData[index] = (item.items)
            })
          }
        })
      }
    },
    // 下一步
    nextStep() {
      if (this.form.title != '' && this.form.template != '') {
        this.activeIndex = '指标内容'
      } else {
        this.$message({
            message: '请完善基本信息',
            type: 'error',
            duration: 1200
        })
        return false
      }
      
    },
    // 提交给后端
    onSubmit() {
      let id = this.$route.params.id=="undefined" ? null : this.$route.params.id
      // 指标内容
      let options = []
      // 总分
      let totalScore = 0
      this.evaGroup.forEach((item,index) => {
        let option = {}
        option.title = item.title
        option.sort = item.sort
        option.items = this.tableData[index]
        option.score = item.score
        options.push(option)
        totalScore += item.score
      })
      // 获取template_id
      let exam_rank_id
      for(let item of this.allTemplate) {
        if (item.title == this.form.template) {
          exam_rank_id = item.id
          break
        }
      }
      let data = {
        id,
        title: this.form.title,
        exam_rank_id,
        options,
        totalScore
      }
      // console.log(data);
      
      this.$http(`markTemplate/${id ? 'updateTemplate' : 'addTemplate'}`, 'post', data, false, resp => {
        if (resp.code == 200) {
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1200
          })
          setTimeout(() => {
            this.$router.push({name: 'ExamTemp', params: {tabClose: true}})
          })
        }
      })
    },
    // 添加和编辑指标组 左上角下拉框确定
    addOrUpdateEvaGroup() {
      let index = this.currentEvaGroup
      if (index == -1) {
        // 增加
        if (this.addEvaGroupTitle != '') {
          this.evaGroup.push({
            title: this.addEvaGroupTitle,
            sort: this.addEvaGroupSort,
            score: 0
          })
          // 给tableData先增加一个空数组
          this.tableData.push([])
          // 清空 + 隐藏
          this.ppCancel()
        } else {
          this.$message({
            message: '请完善添加的信息',
            type: 'error',
            duration: 1200
          })
        }
      } else {
        // 修改
        this.evaGroup[index].title = this.addEvaGroupTitle
        this.evaGroup[index].sort = this.addEvaGroupSort
        this.currentEvaGroup = -1
        // 清空 + 隐藏
        this.ppCancel()
      }
    },
    // 编辑前添加数据
    updateEvaGroup(index) {
      this.addEvaGroupTitle = this.evaGroup[index].title
      this.addEvaGroupSort = this.evaGroup[index].sort
      this.currentEvaGroup = index
      // 显示直接改变ppVisible 不行
      this.$refs.ppLeftTop.show()
    },
    // 左上角下拉框取消
    ppCancel() {
      this.addEvaGroupTitle = ''
      this.addEvaGroupSort = ''
      // this.$refs.ddLeftTop.$.hide()
      this.ppVisible = false
    },
    // 删除指标组
    deleteEvaGroup(index) {
      // 清除table选中
      this.$refs.tableData.clearSelection()
      this.evaGroup.splice(index, 1)
    },
    // 获取考核模板
    getAllTemplate() {
      let data = {
        page: 1,
        length: 1000
      }
      this.$http('rank/selectRankBypages', 'post', data, false, resp => {
        if (resp.code == 200) {
          this.allTemplate = resp.page.list
        }
      })
    },
    // 删除指标
    deleteEvaItem(index) {
      // console.log(this.currentEva);
      // console.log(index);
      this.tableData[this.currentEva].splice(index, 1)
      
    },
    // 当前要显示的指标
    currentShowEva(index) {
      this.currentEva = index
    },
    // 显示从指标库添加指标
    showAddEvaHandle() {
      if (this.evaGroup.length > 0) {
        this.showAddEva = true
        this.$nextTick(() => {
          this.$refs.addEva.init()
        })
      } else {
        this.$message({
          message: '请先添加指标组',
          type: 'warning',
          duration: 1200
        })
      }
    },
    // 更新TableData里的指标数据 (添加指标的回调)
    updateTableData(data) {
      console.log(data);
      data.forEach(item => {
        let f = true
        for (let item2 of this.tableData[this.currentEva]) {
          if (item2.id == item.id) {
            f = false
            break
          }
        }
        if (f) {
          this.tableData[this.currentEva].push(item)
        }
      });
      console.log(this.tableData[this.currentEva]);
      
      // 计算分数
      let sum = 0
      this.tableData[this.currentEva].forEach(item2 => {
        sum += item2.score
      })
      this.evaGroup[this.currentEva].score = sum
    },
  },
  computed: {

  }
}
</script>

<style lang="scss" scoped>
@import './examTemplateAdd.scss';
</style>